package com.tcoiss.common.component.dataentity;

import com.tcoiss.common.core.utils.SpringUtils;
import org.apache.poi.ss.formula.functions.T;

import com.tcoiss.common.component.api.RemoteApiService;

import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class TypesContainer {


    private static Map<Class<?>, Object> instancesDict = new ConcurrentHashMap();

    public static Object getOrRegisterSingletonInstance(String type) {

            Class t = getOrRegister(type);
            if (t != null) {
                Object ret = instancesDict.get(t);
                if (ret == null) {
                    Map arg2 = instancesDict;
                    synchronized (instancesDict) {
                        ret = instancesDict.get(t);
                        if (ret == null) {
                            ret = createInstance(t);
                            instancesDict.put(t, ret);
                        }
                    }
                }

                return ret;
            } else {
                return null;
            }
    }

    public static Class<?> getOrRegister(String type) {
        if (type != null && !type.isEmpty()) {
            try {
                return Class.forName(type.trim());
            } catch (ClassNotFoundException arg1) {
                throw new RuntimeException(String.format("%s: %s not find.", new Object[]{"", type}),
                        arg1);
            }
        } else {
            throw new IllegalArgumentException("type");
        }
    }

    public static void removeRegister(String type) {
    }

    public static <T> T createInstance(String className) {
        Class type = getOrRegister(className);
        if (type == null) {
            throw new RuntimeException(String.format("%1$s failed to  Create Instance.", new Object[]{className}));
        } else {
            return createInstance(type);
        }
    }

    public static <T> T createInstance(Class<?> cls) {
        if (cls == null) {
            throw new RuntimeException(" failed to  Create Instance,Class is Null.");
        } else {
            try {

                return SpringUtils.getBean((Class<T>) cls);
            } catch (Exception arg1) {
                throw new RuntimeException(String.format("%1$s failed to  Create Instance:" + arg1.getMessage(),
                        new Object[]{cls.getName()}), arg1);
            }
        }
    }



}
